package com.gmail.mosoft521.nettyDG.frame.correct;

import com.gmail.mosoft521.nettyDG.util.DateUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeServerHandler extends ChannelHandlerAdapter {

    private int counter;
    private String REQ_INFO = "QUERY TIME ORDER";

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String body = msg.toString();
        System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter);
        String currentTime = REQ_INFO.equalsIgnoreCase(body) ? DateUtils.getCurrentStringDate("yyyy-MM-dd HH:mm:ss") : "BAD ORDER";
        currentTime = currentTime + System.getProperty("line.separator");
        ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
        ctx.writeAndFlush(resp);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }
}